<template>
  <el-dialog v-model="foodStore.foodStepDialog.visible"
             :title="foodStore.foodStepDialog.title"
             center @open="openDialogEvent"
             class="food-step-dialog">
    <el-form ref="formRef" :model="foodStore.foodStepDialog.data"
             :rules="rules">
      <el-form-item label="内容" prop="content">
        <el-input v-model="foodStore.foodStepDialog.data.content" autocomplete="off"
                  placeholder="请输入内容" clearable
                  show-word-limit maxlength="20">
        </el-input>
      </el-form-item>

      <el-form-item label="图片">
        <upload-image v-model="foodStore.foodStepDialog.data.imageUrl"
                      :service-url="fileServiceUrl"
                      :image-limit="1"
                      :service-file-root-path="serviceFileRootPath"
                      :image-path="foodStore.foodImagePath"/>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancelClick">取消</el-button>
        <el-button type="primary" @click="confirmClick">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { UploadImage } from 'vue3-common'
import { useFoodStore } from '@/store/food.ts'
import { ref, reactive, nextTick } from 'vue'
import { FormRules } from 'element-plus'
import { foodStepRules } from '@/utils/element/elRules.ts'
import { fileServiceUrl, serviceFileRootPath } from '@/utils'

const rules = reactive<FormRules>(foodStepRules)

const formRef = ref()
const foodStore = useFoodStore()

/**
 * 打开对话框事件
 */
const openDialogEvent = () => {
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

/**
 * 点击确认按钮
 */
const confirmClick = () => {
  formRef.value.validate()
    .then(async () => {
      if (foodStore.foodStepApiType === 'UPDATE') {
        const { editFoodStepIndex: index } = foodStore
        foodStore.foodRecipeDialog.data.stepList[index] = foodStore.foodStepDialog.data
      } else {
        foodStore.foodRecipeDialog.data.stepList.push(foodStore.foodStepDialog.data)
      }
      foodStore.foodStepDialog.visible = false
    })
}

const cancelClick = () => {
  foodStore.foodStepDialog.visible = false
}
</script>

<style lang="scss">
.food-step-dialog {
  width: 30%;

  .el-dialog__body {
    // height: 50vh;
  }
}
</style>
